package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.properties.WechatConfigProperties;
import com.zzyl.service.WechatService;
import com.zzyl.utils.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

    @Autowired
    private WechatConfigProperties wechatProperties;

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    /**
     * 获取微信用户openid
     * @param code 临时登录凭证
     * @return
     */
    @Override
    public String getOpenId(String code) {
        //设置请求的参数
        Map<String, Object> requestParam  = getAppConfig();
        requestParam.put("js_code",code);

        //向微信第三方接口发送get请求
        String result = HttpUtil.get(REQUEST_URL, requestParam);

        //将返回的json字符串解析为java对象
        JSONObject jsonObject = JSONUtil.parseObj(result);

        //若errcode不为空，则获取不到openid，响应失败
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        //获取微信用户openid
        String openid = jsonObject.getStr("openid");
        return openid;

    }


    /**
     * 获取微信用户手机号phone
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhone(String phoneCode){
        //设置请求的参数
        Map<String, Object> requestParam  = new HashMap<>();
        requestParam.put("code",phoneCode);

        //设置请求路径
        String url = PHONE_REQUEST_URL + getToken();

        String result = HttpUtil.post(url, JSONUtil.toJsonStr(requestParam));
        JSONObject jsonObject = JSONUtil.parseObj(result);

        //如果响应的errcode不是0，则响应数据失败
        if (jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        //获取jsonObject对象中phone_info对象
        JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
        //返回微信用户绑定的手机号
        return phoneInfo.getStr("phoneNumber");

    }


    /**
     * 获取请求微信用户手机号的凭证
     * @return
     */
    public String getToken(){
        //设置请求的参数
        Map<String, Object> requestParam  = getAppConfig();

        //向微信第三方接口发送get请求
        String result = HttpUtil.get(TOKEN_URL, requestParam);

        JSONObject jsonObject = JSONUtil.parseObj(result);

        //若errcode不为空，则获取不到openid，响应失败
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        String token = jsonObject.getStr("access_token");
        return token;
    }


    /**
     * 封装公共参数
     * @return
     */
    private Map<String, Object> getAppConfig() {

        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", wechatProperties.getAppID());
        requestUrlParam.put("secret",wechatProperties.getAppSecret());
        return requestUrlParam;
    }
}
